import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { useRouter } from 'next/router';
import axios from 'axios';
import { Pagination, Alert, Input, List, Row, Col } from 'antd';

//导航栏基本样式
const Nav = styled.nav`
      background-color: rgb(255, 102, 0);
  padding: 10px;
`;
const Ul1 = styled.ul`
  display: flex;
  list-style-type: none;
  margin: 0;
  padding: 0;
`;
const Li = styled.li`
  margin-right: 10px;
`;
const Link = styled.a`
  color: #333;
  text-decoration: none;
  padding: 5px;
  border-radius: 4px;

  &:hover {
    background-color: #ddd;
  }
`;

const About = () => {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState('');        //搜索框的值
  const [news, setNews] = useState([]);   //接口请求的最新数据
  const [filteredData, setFilteredData] = useState<any>();   //搜索过滤后的数据
  const { query } = router.query as any;   //传达的参数
  interface DataItem {
    id: number;
    title: string;
  }
  const { Search } = Input;
  const [currentPage, setCurrentPage] = useState(1);
  const BaseNumber = (currentPage - 1) * 30   //计算编号

  //请求数据
  useEffect(() => {
    fetchNews(currentPage)
  }, [])

  //请求数据的方法抽离
  async function fetchNews(page: any) {
    try {
      const response = await axios.get(`https://api.hnpwa.com/v0/news/${page}.json`).then((response) => { setNews(response.data); })
      // setNews(response.data);
      return response
      // setTotalPages(response.headers['x-total-pages']);
    } catch (error) {
      return (<Alert message="请求数据失败" type="error" />)
    }
  }

  //搜索后对方法的过滤
  useEffect((): any => {
    fetchNews(currentPage)
    console.log(news.length, 'news');
    const Data: DataItem[] = news.filter((item: any) =>
      item?.title.toLowerCase().includes(query?.toString().toLowerCase() ?? '')
    );
    console.log(Data, 'Data');
    setFilteredData(Data)
  }, [query, currentPage]);

  //当情况为0的时候
  // if (news.length == 0) {
  //   // fetchNews(currentPage+1)
  //   // router.push({
  //   //   pathname: '/about',
  //   //   query: { query: query }
  //   // });
  //   // alert('Condition is true');
  //   // return (<><Alert message="系统繁忙，刷新页面重新请求" type="error" /></>)
  // }
  // console.log(filteredData, 'filteredData');

  //改变页码
  function handlePageChange(e: number) {
    setCurrentPage(e)
  }
  const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setSearchTerm(e.target.value);
    // console.log(e.target.value, 'searchTerm')
  }

  //高亮设置
  function highlightSearchText(text: string, query: string): any {
    const regex = new RegExp(`(${query})`, 'gi');
    const parts = text.split(regex);

    return parts.map((part, index) =>
      regex.test(part) ? <mark key={index}>{part}</mark> : part
    );
  }

  //搜索功能
  const onSearch = (value: string) => {
    // console.log(searchTerm,'/////////////////////')
    router.push({
      pathname: '/search',
      query: { query: searchTerm }
    });
  }

  //切换主题   未完成
  interface ThemeButtonProps {
    isDarkTheme: boolean;
  }
  const ThemeButton = styled.button<ThemeButtonProps>`
  background-color: ${props => (props.isDarkTheme ? '#000000' : '#ffffff')};
  color: ${props => (props.isDarkTheme ? '#ffffff' : '#000000')};
  border: none;
  outline: none;
  cursor: pointer;
`;
  const [isDarkTheme, setIsDarkTheme] = useState(false);

  // 切换主题的处理函数
  const toggleTheme = () => {
    setIsDarkTheme(prevTheme => !prevTheme);
  };
  return (
    <Row justify="center" align="middle">
      <Col span={18}>
        <Nav>
          <Ul1>
            <Li>
              <Link href="/">Home</Link>
            </Li>
            <Li>
              <Link href="/about">About</Link>
            </Li>
            <Li>
              <Link href="/services">new</Link>
            </Li>
            <Li>
              <Link href="/contact">past</Link>
            </Li>
            <Li>
              <Link href="/contact">comments</Link>
            </Li>
            <Li>
              <Link href="/contact">ask</Link>
            </Li>
            <Li>
              <Link href="/contact">show</Link>
            </Li>
            <Li>
              <Link href="/contact">jobs</Link>
            </Li>
            <Li>
              <Link href="/contact">submit</Link>
            </Li>
            <Li>
              <ThemeButton isDarkTheme={isDarkTheme} onClick={toggleTheme}>
                切换主题
              </ThemeButton>
            </Li>
          </Ul1>
        </Nav>
        <Search
          placeholder="input search text"
          allowClear
          enterButton="Search"
          size="large"
          onChange={onChange}
          onSearch={onSearch}
        />
        {news.length > 0 ? <>
          <List
            dataSource={news.filter((item: any) =>
              item?.title.toLowerCase().includes(query?.toString().toLowerCase() ?? ''))}
            renderItem={(item: any, index: number) => (
              <List.Item>
                <List.Item.Meta
                  title={<a href={item.url} target="_blank">NO.{BaseNumber + index + 1}  {highlightSearchText(item.title, query)} </a>}
                  description="Ant Design, a design language for background applications, is refined by Ant UED Team"
                />
              </List.Item>
            )}
          />
          <div>
            <Pagination
              current={currentPage}
              total={100} // 总数据条数
              pageSize={10} // 每页显示的数据条数
              onChange={handlePageChange} // 切换页码时的回调函数
            />
          </div></> : <>数据还未加载</>
        }
      </Col>
    </Row>
  );
}

export default About;
